<template>
  <div class="instance-demo">
    <div class="main-content">
      <!-- 像素流接入根节点 -->
      <div id="pixel-stream-root"></div>

      <!-- 操作面板 -->
      <div class="control-panel" :class="{ collapsed: isPanelCollapsed }">
        <div class="panel-toggle" @click="togglePanel">
          <div class="toggle-button">
            <el-icon :size="20" :class="{ 'rotate-180': !isPanelCollapsed }">
              <ArrowRightBold />
            </el-icon>
          </div>
        </div>

        <div class="panel-content">
          <!-- 代码展示区域 -->
          <div class="code-section">
            <div class="code-header">
              <div class="header-title">代码编辑器</div>
              <div class="header-actions">
                <el-button type="primary" size="small" @click="runCode">
                  <el-icon><VideoPlay /></el-icon> 运行
                </el-button>
                <el-button size="small" @click="resetCode">
                  <el-icon><RefreshRight /></el-icon> 重置
                </el-button>
              </div>
            </div>
            <div class="code-editor">
              <MonacoEditor
                v-model="currentCode"
                :options="editorOptions"
                language="javascript"
                theme="vs-dark"
                @change="onChange"
              />
            </div>
          </div>

          <!-- API列表 -->
          <div class="api-list">
            <div class="list-header">可用API</div>
            <el-scrollbar>
              <div class="api-items">
                <template v-for="category in SDKMenu" :key="category.sdkCategory">
                  <div 
                    class="category-header" 
                    @click="toggleCategory(category.sdkCategory)"
                  >
                    <el-icon class="expand-icon" :class="{ expanded: expandedCategories[category.sdkCategory] }">
                      <ArrowRightBold />
                    </el-icon>
                    <el-icon class="category-icon"><Connection /></el-icon>
                    <span class="category-title">{{ category.categoryName }}</span>
                  </div>
                  <div 
                    v-show="expandedCategories[category.sdkCategory]"
                    class="method-list"
                  >
                    <div
                      v-for="method in category.methodsList"
                      :key="method._id"
                      class="api-item"
                      :class="{ active: currentApi === method.methodName }"
                      @click="selectApiMethod(method._id)"
                    >
                      <span class="method-name">{{ method.methodName }}</span>
                    </div>
                  </div>
                </template>
              </div>
            </el-scrollbar>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, defineAsyncComponent } from "vue";
import { useRoute } from "vue-router";
import {
  ArrowRightBold,
  VideoPlay,
  RefreshRight,
  Connection,
} from "@element-plus/icons-vue";
import { ElMessage } from "element-plus";
import { useCreateUEInstance } from "@/hooks/ue/useCreateUEInstance.js";
import { getSdkList, getSdkDetail } from "@/api/modules/ueSdk";

// 异步加载Monaco Editor组件
const MonacoEditor = defineAsyncComponent(() =>
  import("@/components/MonacoEditor.vue")
);

// 获取路由参数
const route = useRoute();
const { url, instanceId, name } = route.query;
console.log("route", url, instanceId, name);
// 初始化UE实例
let ueInstance = null;

// if (!url) {
//   ElMessage.error("缺少必要的实例连接信息");
//   return;
// }

ueInstance = useCreateUEInstance(
  {
    dom: "pixel-stream-root",
    url,
  },
  () => {
    ElMessage.success(`实例 ${name || "Unknown"} 连接成功`);
    console.log("ueInstance ready", ueInstance);
  }
);

// 面板折叠状态
const isPanelCollapsed = ref(false);

// 当前选中的API和代码
const currentApi = ref("");
const currentCode = ref("");
const originalCode = ref("");

// SDK列表数据
const SDKMenu = ref([]);

// 分类展开状态
const expandedCategories = ref({});

// Monaco Editor 配置
const editorOptions = {
  minimap: { enabled: false },
  fontSize: 14,
  lineHeight: 22,
  fontFamily: '"JetBrains Mono", Consolas, "Courier New", monospace',
  scrollBeyondLastLine: false,
  automaticLayout: true,
  tabSize: 2,
  renderLineHighlight: "all",
  padding: { top: 16, bottom: 16 },
  suggest: {
    showKeywords: true,
  },
};

// 初始化SDK列表
const initSDKList = async () => {
  try {
    const res = await getSdkList();
    SDKMenu.value = res.data;
    // 初始化展开状态，默认展开第一个分类
    const initialExpanded = {};
    SDKMenu.value.forEach((category, index) => {
      initialExpanded[category.sdkCategory] = index === 0;
    });
    expandedCategories.value = initialExpanded;
  } catch (error) {
    console.error("获取SDK列表失败:", error);
    ElMessage.error("获取SDK列表失败");
  }
};

// 切换面板显示状态
const togglePanel = () => {
  isPanelCollapsed.value = !isPanelCollapsed.value;
};

// 切换分类展开状态
const toggleCategory = (categoryId) => {
  expandedCategories.value[categoryId] = !expandedCategories.value[categoryId];
};

// 选择API方法
const selectApiMethod = async (methodId) => {
  try {
    const res = await getSdkDetail({ id: methodId });
    const methodDetail = res.data;
    currentApi.value = methodDetail.methodName;
    currentCode.value = methodDetail.callExample || "";
    originalCode.value = methodDetail.callExample || "";
  } catch (error) {
    console.error("获取API详情失败:", error);
    ElMessage.error("获取API详情失败");
  }
};

// 代码改变事件
const onChange = (value) => {
  currentCode.value = value;
};

// 运行代码
const runCode = async () => {
  if (!ueInstance) {
    ElMessage.error("UE实例未初始化，请等待连接成功后再试");
    return;
  }

  try {
    await eval(`(async () => { ${currentCode.value} })()`);
    ElMessage.success("代码执行成功");
  } catch (error) {
    console.error("代码执行错误:", error);
    ElMessage.error(`执行错误: ${error.message}`);
  }
};

// 重置代码
const resetCode = () => {
  currentCode.value = originalCode.value;
  ElMessage.info("代码已重置");
};

// 初始化
onMounted(async () => {
  await initSDKList();
  // 如果有SDK数据，默认选择第一个方法
  if (SDKMenu.value.length > 0 && SDKMenu.value[0].methodsList.length > 0) {
    await selectApiMethod(SDKMenu.value[0].methodsList[0]._id);
  }
});
</script>

<style scoped>
.instance-demo {
  height: calc(100vh - 60px);
  overflow: hidden;
  position: relative;
  background: #1e1e1e;
}

.main-content {
  height: 100%;
  position: relative;
}

#pixel-stream-root {
  width: 100%;
  height: 100%;
  background: #000;
}

.control-panel {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 360px;
  background: #252526;
  box-shadow: 2px 0 8px rgba(0, 0, 0, 0.3);
  transition: transform 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
}

.control-panel.collapsed {
  transform: translateX(-100%);
}

.panel-toggle {
  position: absolute;
  right: -40px;
  top: 50%;
  transform: translateY(-50%);
  z-index: 10;
}

.toggle-button {
  width: 40px;
  height: 80px;
  background: #252526;
  border-radius: 0 6px 6px 0;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  box-shadow: 4px 0 8px rgba(0, 0, 0, 0.1);
  color: #fff;
  transition: background-color 0.3s;
}

.toggle-button:hover {
  background: #2d2d2d;
}

.rotate-180 {
  transform: rotate(180deg);
}

.panel-content {
  flex: 1;
  height: 100%;
  display: flex;
  flex-direction: column;
  overflow: hidden;
}

.code-section {
  flex: 1;
  display: flex;
  flex-direction: column;
  border-bottom: 1px solid #333;
  overflow: hidden;
}

.code-header {
  padding: 12px 16px;
  background: #2d2d2d;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-title {
  color: #fff;
  font-size: 14px;
  font-weight: 500;
}

.header-actions {
  display: flex;
  gap: 8px;
}

.code-editor {
  flex: 1;
  overflow: hidden;
  border-radius: 4px;
  background: #1e1e1e;
}

.api-list {
  height: 440px;
  background: #252526;
  display: flex;
  flex-direction: column;
}

.list-header {
  padding: 12px 16px;
  color: #fff;
  font-size: 14px;
  font-weight: 500;
  background: #2d2d2d;
}

.api-items {
  padding: 8px;
}

/* 一级分类样式 */
.category-header {
  padding: 12px 16px;
  margin: 8px 0 4px 0;
  color: #fff;
  font-size: 16px;
  font-weight: 600;
  background-color: #2d2d2d;
  border-radius: 6px;
  display: flex;
  align-items: center;
  gap: 10px;
  cursor: pointer;
  transition: all 0.3s ease;
  user-select: none;
}

.category-header:hover {
  background-color: #3a3a3a;
  transform: translateX(2px);
}

.expand-icon {
  font-size: 12px;
  color: #ccc;
  transition: transform 0.3s ease;
}

.expand-icon.expanded {
  transform: rotate(90deg);
}

.category-icon {
  font-size: 18px;
  color: #409eff;
}

.category-title {
  flex: 1;
  font-weight: 600;
}

/* 方法列表容器 */
.method-list {
  margin-left: 16px;
  border-left: 2px solid #3a3a3a;
  padding-left: 8px;
  margin-bottom: 8px;
}

/* 二级方法项样式 */
.api-item {
  padding: 8px 16px;
  margin: 2px 0;
  cursor: pointer;
  transition: all 0.2s ease;
  border-radius: 4px;
  color: #ccc;
  display: flex;
  align-items: center;
  position: relative;
  font-size: 13px;
}

.api-item::before {
  content: '';
  position: absolute;
  left: 8px;
  top: 50%;
  transform: translateY(-50%);
  width: 6px;
  height: 6px;
  background-color: #666;
  border-radius: 50%;
  transition: all 0.2s ease;
}

.api-item:hover {
  background-color: #2d2d2d;
  color: #fff;
  transform: translateX(4px);
}

.api-item:hover::before {
  background-color: #409eff;
  transform: translateY(-50%) scale(1.2);
}

.api-item.active {
  background-color: #37373d;
  color: #fff;
  border-left: 3px solid #409eff;
}

.api-item.active::before {
  background-color: #409eff;
  transform: translateY(-50%) scale(1.3);
  box-shadow: 0 0 8px rgba(64, 158, 255, 0.5);
}

.method-name {
  margin-left: 16px;
  font-weight: 400;
}

:deep(.el-scrollbar__view) {
  padding: 8px;
}

:deep(.monaco-editor) {
  padding-top: 8px;
}

:deep(.monaco-editor .margin) {
  background: #1e1e1e;
}
</style>
